/*
* 包含 n 个接口的请求函数模块
* 每个函数返回值为: Promise
* */
import jsonp from 'jsonp'
import { message } from 'antd'
import ajax from './ajax'

/*
* 请求登录接口
* */
export const reqLogin = (username, password) => ajax('/login', { username, password }, 'POST')

/*
* jsonp 请求的接口请求函数
* 请求天气接口
* */
export const reqWeather = (city) => {
  return new Promise((resolve, reject) => {
    const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p4
9MVra6urFRGOT9s8UBWr2`
    // 发送 jsonp 请求
    jsonp(url, {}, (err, data) => {
      // console.log('jsonp()', err, data)
      if (!err && data.status === 'success') {
        // 成功
        // 取出需要的数据
        const { dayPictureUrl, weather } = data.results[0].weather_data[0]
        resolve({ dayPictureUrl, weather })
      } else {
        // 失败
        message.error('获取天气信息失败')
      }
    })
  })
}

/*
* 获取一级分类或二级分类的列表
* */
export const reqCategories = (parentId) => ajax('/manage/category/list', { parentId })

/*
* 添加分类
* */
export const reqAddCategory = (parentId, categoryName) => ajax('/manage/category/add', { parentId, categoryName }, 'POST')

/*
* 更新分类
* */
export const reqUpdateCategory = (categoryId, categoryName) => ajax('/manage/category/update', { categoryId, categoryName }, 'POST')

/*
* 删除分类(根据 _id 值)
* */
export const reqRemoveCategory = (_id) => ajax('/manage/category/remove', { _id })

/*
* 获取一个分类
* */
export const reqCategory = (categoryId) => ajax('/manage/category/info', { categoryId })

/*
* 获取商品分页列表
* */
export const reqProducts = (pageNum, pageSize) => ajax('manage/product/list', { pageNum, pageSize, })

/*
* 搜索商品分页列表(根据 id 或 name)
* searchType: 搜索的类型, productName/productDesc
* */
export const reqSearchProducts = ({pageNum, pageSize, searchName, searchType}) => ajax('/manage/product/search', {
  pageNum,
  pageSize,
  [searchType]: searchName,
})

/*
* 更新商品状态(上架/下架)
* */
export const reqUpdateStatus = ({ productId, status }) => ajax('/manage/product/updateStatus', { productId, status }, 'POST')

/*
* 删除图片
* */
export const reqDeleteImg = (name) => ajax('/manage/img/delete', { name }, 'POST')

/*
* 添加/修改商品
* */
export const reqAddOrUpdateProduct = (product) => ajax('/manage/product/' + (product._id ? 'update' : 'add'), product, 'POST')

/*
* 删除商品(根据产品id)
* */
export const reqRemoveProduct = (productId) => ajax('/manage/product/remove', {productId})

/*
* 获取所有角色的列表
* */
export const reqRoles = () => ajax('/manage/role/list')

/*
* 添加角色
* */
export const reqAddRole = (roleName) => ajax('/manage/role/add', { roleName }, 'POST')

/*
* 更新角色
* */
export const reqUpdateRole = (role) => ajax('/manage/role/update', role , 'POST')

/*
* 获取用户列表
* */
export const reqUsers = () => ajax('/manage/user/list')

/*
* 添加/更新用户
* */
export const reqAddOrUpdateUser = (role) => ajax('/manage/user/' + (role._id ? 'update' : 'add'), role, 'POST')

/*
* 删除用户
* */
export const reqRemoveUsers = (userId) => ajax('/manage/user/delete', { userId }, 'POST')


